const db = require("../db/index");
const jwt = require("jsonwebtoken");
const { secretKey, expiresIn } = require("../config/index");
const { formatDateTime } = require("../tools/dateFormat");
const axios = require("axios");
const codeAppId = "tws8coilqsewusip";
const codeAppSecret = "1fjdxl0feHWSzDwi6nQJZEZ64K9ruHfc";
const { aes } = require("../tools/aes");

//上传用户签到
exports.sendUserCheckin = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    // const sql = "INSERT INTO checkin (userId) VALUES (?)"
    const sql = "SELECT * FROM checkin WHERE userId = ?";
    const userSql = "SELECT * FROM user WHERE userId = ?";
    db.query(userSql, data.userId, (userErr, userRes) => {
      const userInfo = userRes[0];
      db.query(sql, data.userId, (err, results) => {
        console.log(results, err, "sql results");
        if (results.length !== 1) {
          //没有找到此用户的上传记录，新建一条
          if (userRes.length !== 1) {
            res.send({
              status: 500,
              message: "未找到用户信息",
              // data:results
            });
          } else {
            console.log(userInfo, "userInfo");
            const sqlInner =
              "INSERT INTO checkin (userId,count,name,userImage,lat,lng) VALUES (?,?,?,?,?,?)";
            db.query(
              sqlInner,
              [
                data.userId,
                "1",
                userInfo.name,
                userInfo.userImage,
                userInfo.lat,
                userInfo.lng,
              ],
              (err, results) => {
                if (err) {
                  console.log(err, "err");
                  return res.send({ status: 500, message: "上传签到信息失败" });
                }
                console.log(results, "sql results");
                res.send({
                  status: 200,
                  message: "上传签到信息成功",
                  // data:results
                });
              }
            );
          }
        } else {
          //有用户信息，签到次数加1
          const info = results[0];
          console.log(info, "info");
          var count = info.count + 1;
          const sqlInner =
            "UPDATE checkin set count=?,userImage=?,name=? WHERE userId=?";
          db.query(
            sqlInner,
            [count, userInfo.userImage,userInfo.name, info.userId],
            (err, results) => {
              console.log(results, err, "sql results");
              if (err) {
                res.send({
                  status: 500,
                  message: "上传签到信息失败",
                });
              } else {
                res.send({
                  status: 200,
                  message: "上传签到信息成功",
                });
              }
            }
          );
        }
      });
    });
  });
};

//获取签到列表
exports.getUserCheckin = (req, res) => {
  console.log(req.headers.authorization.slice(7), "req");
  const token = req.headers.authorization.slice(7);
  if (token == null) {
    res.send({
      status: 500,
      message: "token错误",
    });
    return;
  }
  jwt.verify(token, secretKey, (err, data) => {
    if (err) {
      res.send({
        status: 500,
        message: "token解析失败",
      });
      return;
    }
    console.log(data, "jwt解析");
    const sql = "SELECT * FROM checkin ORDER BY count DESC LIMIT 50";
    db.query(sql, (err, results) => {
      console.log(results, err, "results");
      if (err) {
        res.send({
          status: 500,
          message: "获取签到列表失败",
        });
      } else {
        res.send({
          status: 200,
          message: "获取签到列表成功",
          data: results,
        });
      }
    });
  });
};

exports.barCodeMsg = (req, res) => {
  // console.log(req.headers.authorization.slice(7), "req");
  const { key, code } = req.body;
  const customTime = parseFloat(aes.decrypt(key));
  const currentTime = parseFloat((new Date().getTime() / 1000).toFixed(0));
  // console.log(customTime,currentTime,'barCodemsg')
  if (Math.abs(currentTime - customTime) > 30) {
    res.send({
      status: 500,
      message: "数据解密失败",
    });
  } else {
   
    axios
      .get(
        `https://www.mxnzp.com/api/barcode/goods/details?barcode=${code}&app_id=${codeAppId}&app_secret=${codeAppSecret}`
      )
      .then((result) => {
        // console.log("barCode解析数据",result.data.data || {})
        res.send({
          status: 200,
          message: "获取信息成功",
          data: result.data.data || {},
        });
      })
      .catch((error) => {
        console.log("barCode error", error);
        res.send({
          status: 500,
          message: "获取信息失败，请稍后再试",
        });
      });
  }
};
